package com.ramos.kuaixiao.utils;

import android.content.Context;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.entity.AddressInfo;

public class StartLocation implements AMapLocationListener {
    private final static String TAG = "StartLocation";
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private AddressInfo myLocationInfo;

    public StartLocation(Context context) {
        mlocationClient = new AMapLocationClient(App.mContext);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(5000);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
    }

    public AddressInfo getAddress() {
        return myLocationInfo;
    }

    public void startLocation() {
        mlocationClient.startLocation();
    }

    public void stotLocation() {
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        myLocationInfo = new AddressInfo();
        myLocationInfo.mainAddress = amapLocation.getPoiName();
        myLocationInfo.descAddress = amapLocation.getAddress();
        myLocationInfo.latitude = amapLocation.getLatitude();
        myLocationInfo.longitude = amapLocation.getLongitude();
        myLocationInfo.city = amapLocation.getCity();

        //Log.d(TAG, "onLocationChanged:" + myLocationInfo.latitude + " " + myLocationInfo.longitude);
        SharedPreference.setPreferString("latitude", myLocationInfo.latitude + "");
        SharedPreference.setPreferString("longitude", myLocationInfo.longitude + "");
        SharedPreference.setPreferString("descAddress", myLocationInfo.descAddress);
        SharedPreference.setPreferString("city", myLocationInfo.city);
        SharedPreference.setPreferString("time", String.valueOf(amapLocation.getTime()));
    }

}
